//
//  AppDelegate.m
//  DoctorProject
//
//  Created by zhibao on 2021/11/3.
//

#import "AppDelegate.h"
#import "LNavigationViewController.h"
#import <StoreKit/StoreKit.h>
#import <ATAuthSDK/ATAuthSDK.h>

@interface AppDelegate ()<SKPaymentTransactionObserver>

@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UMConfigure initWithAppkey:@"672a2a217e5e6a4eeb8e3fca" channel:@"APP Store"];
    [MobClick setAutoPageEnabled:YES];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.enableAutoToolbar = YES;
    
    UITableView.appearance.estimatedRowHeight = 0;
    UITableView.appearance.estimatedSectionFooterHeight = 0;
    UITableView.appearance.estimatedSectionHeaderHeight = 0;
    if (@available(iOS 15.0, *)) {
        UITableView.appearance.sectionHeaderTopPadding = 0.0;
    } else {
        // Fallback on earlier versions
    }
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = UIColor.clearColor;
    if([UserInfoManager sharedManager].isLogin){
        [[UserInfoManager sharedManager] getUserInfoData:^(BOOL flag) {
            
        }];
    }

    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    //[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
    /*
     * 初始化
     */
    
    //导航
    [self setNavConfig];
    //初始化
    [self setTabbarController];
    
    [self.window makeKeyAndVisible];
    
//    NSDate *oldTime =  [[NSUserDefaults standardUserDefaults]objectForKey:@"storeStarTime"];
//    if (oldTime) {
//        //利用NSCalendar比较日期的差异
//        NSCalendar *calendar = [NSCalendar currentCalendar];
//        
//        NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
//        //比较的结果是NSDateComponents类对象
//        NSDateComponents *delta = [calendar components:unit fromDate:oldTime toDate:[NSDate date] options:0];
//        NSInteger flag = [[NSUserDefaults standardUserDefaults] integerForKey:@"Integer"];
//        DLog(@"%@ %ld %ld",oldTime,(long)delta.day,(long)flag);
//        if (delta.day >= 7 * (flag + 1)) {
//            [self showStore];
//            [[NSUserDefaults standardUserDefaults] setInteger:flag + 1 forKey:@"Integer"];
//        }
//    }else{
//        [[NSUserDefaults standardUserDefaults]setObject:[NSDate date] forKey:@"storeStarTime"];
//    }
    
    [[TXCommonHandler sharedInstance] setAuthSDKInfo:PNSATAUTHSDKINFO
                                            complete:^(NSDictionary * _Nonnull resultDic) {
        NSLog(@"设置秘钥结果：%@", resultDic);
    }];
    
    return YES;
}

-(void)showStore{
    if (@available(iOS 10.3, *)) {
        if([SKStoreReviewController respondsToSelector:@selector(requestReview)]) {// iOS 10.3 以上支持
            //防止键盘遮挡
            [[UIApplication sharedApplication].delegate.window endEditing:YES];
            [SKStoreReviewController requestReview];
        }else{
            NSString * nsStringToOpen = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?action=write-review",@"6443703983"];//替换为对应的APPID
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:nsStringToOpen] options:@{} completionHandler:^(BOOL success) {
                
            }];
        }
        
    } else {
        NSString * nsStringToOpen = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?action=write-review",@"6443703983"];//替换为对应的APPID
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:nsStringToOpen] options:@{} completionHandler:^(BOOL success) {
            
        }];
    }
    [[NSUserDefaults standardUserDefaults]setObject:[NSDate date] forKey:@"storeStarTime"];
}

- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product{
    return NO;
}

- (void)setTabbarController {
    
    NSString *tempFirstStr = [[NSUserDefaults standardUserDefaults] valueForKey:WelcomeFlag];
    MYAPP.window.rootViewController = [UIViewController new];
    DLog(@"eeeee===%@",[UserInfoManager sharedManager].vip_expiry_date);
    if ([Helper validateWithStartTime:@"2022-11-09 17:00:00" withExpireTime:@"2024-11-26 08:00:00"]) {
        [MYGlobal share].wechatFlag = 1;
    }
    
    if (tempFirstStr.length > 4) {
        MyTabBarController *tabbarController = [[MyTabBarController alloc] init];
        MYAPP.tarbar = tabbarController;
        self.window.rootViewController = tabbarController;
//        if([UserInfoManager sharedManager].vip_expiry_date.length > 2){
//            MyTabBarController *tabbarController = [[MyTabBarController alloc] init];
//            MYAPP.tarbar = tabbarController;
//            self.window.rootViewController = tabbarController;
//        }else{
//            PopPayController *controller = [[PopPayController alloc] init];
//            LNavigationViewController *nav = [LNavigationViewController rootVC:controller];
//            nav.gk_openScrollLeftPush = YES;
//            nav.gk_openSystemNavHandle = YES;
//            MYAPP.window.rootViewController = nav;
//        }
    }else{
        MYAPP.window.rootViewController = [WelcomeController new];
    }
}

- (void)setNavConfig {
    //    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    // 配置导航栏属性
    [GKConfigure setupCustomConfigure:^(GKNavigationBarConfigure *configure) {
        //       configure.gk_translationX = 15;
        //       configure.gk_translationY = 20;
        configure.backgroundColor = MyColor(@"#000000");
        configure.titleFont = MY_SCALE_RegularFONT(18);
        configure.titleColor = UIColor.whiteColor;
        //       configure.gk_scaleX = 0.90;
        configure.backImage = [UIImage imageNamed:@"arrow_back_white"];
        //       configure.gk_scaleY = 0.92;
        configure.gk_navItemLeftSpace = 12.0f;
        configure.gk_navItemRightSpace = 12.0f;
    }];
}

-(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable restorableObjects))restorationHandler NS_AVAILABLE_IOS(8_0); {
    
    return YES;
}


- (void)applicationDidBecomeActive:(UIApplication *)application{
    
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    return YES;
}


#pragma mark - 程序将要进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {
    DLog(@"程序将要进入前台");
}

- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
    if(![UserInfoManager sharedManager].isLogin){
        return;
    }
    if(transactions.count > 0){
        SKPaymentTransaction *tran = transactions.lastObject;
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
                NSLog(@"交易完成");
                [self verifyPurchaseWithPaymentTransaction:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"已经购买过商品");
                break;
            case SKPaymentTransactionStateFailed:
                NSLog(@"交易失败");
                
                break;
            default:
                break;
        }
    }
}
- (void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction{
    //交易验证
//    NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
//    NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
//    if(!receipt){
//        return;
//    }
//    NSString *idkey = [DWKeychainTool getItemForKey:@"id"];
//    NSString *time = [Helper getTime:TimeTypeZhou];
//    if([idkey isEqualToString:@"com.yuliang.jianting.yue"]){
//        time = [Helper getTime:TimeTypeYue];
//    }else if([idkey isEqualToString:@"com.yuliang.jianting.ji"]){
//        time = [Helper getTime:TimeTypeJi];
//    }else if([idkey isEqualToString:@"com.yuliang.jianting.nian"]){
//        time = [Helper getTime:TimeTypeNian];
//    }
//    [DWKeychainTool saveItem:time key:@"vip"];
//    [[UserInfoManager sharedManager] getUserInfoData:^(BOOL flag) {
//        
//    }];
}

@end
